package main

import (
	"fmt"
	"github.com/urfave/cli"
	"github.com/peterh/liner"
	"github.com/gobs/args"
	"os"
	"baiduDownload/api"
)
//定义当前目录
var path []string

func urlCat() string {
	//拼接url
	returnUrl := ""
	for _, url := range(path) {
		returnUrl += url 
	}
	return returnUrl
}

func main() {
	app := cli.NewApp()
    // app.Name = "sysconfig"
    // app.Usage = "Setting basic configuration"
	// app.Version = "0.0.1"
	
	app.Commands = []*cli.Command {
		{
			Name: "user login",
			Aliases: []string{"login"},
			Action: func(c *cli.Context) error {
				fmt.Println("action login!")
				fmt.Println(c.String("username"))
				fmt.Println(c.String("password"))
				// fmt.Println(c.Args().Get(0))
				return nil 
			},
			Flags: []cli.Flag {
				&cli.StringFlag {
					Name: "username",
					Usage: "用户名",
				},

				&cli.StringFlag {
					Name:  "password",
					Usage: "密码",
				},

			},
		},

		{
			Name: "quit app",
			Aliases: []string{"quit"},
			Action: func(c *cli.Context) error {
				fmt.Println("bye~")
				os.Exit(0)
				return nil 
			},
		},

		{	
			//ls 命令
			Name: "ls files and dirs",
			Aliases: []string{"ls"},
			Action: func(c *cli.Context) error {
				api.LSCommand(urlCat())
				return nil 
			},
		},
		
		{	
			//help 命令
			Name: "ls files and dirs",
			Aliases: []string{"help"},
			Action: func(c *cli.Context) error {
				fmt.Println("1. 输入 quit 可以退出")
				fmt.Println("2. 支持 ls：查看当前目录下的所有文件夹和文件")
				fmt.Println("3. 支持 cd 目录 ： 进入某个目录")
				fmt.Println("4. 支持 cd .. ：返回上一级目录")
				fmt.Println("5. 使用 get 文件名 ：可以获取百度云下载连接，之后使用wget命令下载即可")
				return nil 
			},
		},

		{	
			//cd 命令
			Name: "cd command",
			Aliases: []string{"cd"},
			Action: func(c *cli.Context) error {
				if c.NArg() == 0 {
					fmt.Println("没有输入目录")
					return nil
				}
				cmd := c.Args().Get(0)
				if string(cmd) == ".." {
					//退回上一级
					if len(path) == 1 {
						//说明已经在根目录了
						fmt.Println("位于根目录，无法返回上一级")
						return nil 
					}
					path = path[: len(path) - 1]
					fmt.Println("成功！" + "当前目录:" + urlCat())
					return nil 
				} else {
					//检查有没有这个目录
					if api.ExistDir(urlCat(), string(cmd)) {
						//存在这个目录
						path = append(path, cmd + "/")
						fmt.Println("cd成功！当前目录:" + urlCat())
					} else {
						fmt.Println("目录不存在！")
						return nil 
					}
				}
				
				return nil 
			},
		},

		{	
			//downllsoad 命令
			Name: "get file url ",
			Aliases: []string{"get"},
			Action: func(c *cli.Context) error {
				cmd := c.Args().Get(0)
				dlink := api.GetUrl(cmd, urlCat())
				fmt.Println("下载地址为：" + dlink)
				return nil 
			},
		},

		{
			//upload file 命令
			Name: "upload file",
			Aliases: []string{"upload"},
			Action: func(c *cli.Context) error {
				cmd := c.Args().Get(0)
				hashList, fileList, size, name, err := api.ReadBigFile(cmd)//传入文件路径
				if err != nil {
					return err
				}
				returns := api.PreUpload(name, size, hashList)
				returnMD5List := api.SliceUpload(returns, fileList, hashList)
				// fmt.Println(returnMD5List)
				api.CreateFile(returnMD5List, size, returns.UploadId, returns.FileName)
				return nil
				 
			},
		},


	}

    app.Action = func(c *cli.Context) error {
		path = append(path, "/")
		fmt.Println("正在获取用户信息......")
		// 用户登陆，获取用户信息
		api.GetUserInfo()
		fmt.Println("输入 help 即可查看帮助....")
		line := liner.NewLiner()
		
		// api.LSCommand(urlCat())

		for {
			if cmd, err := line.Prompt("baiduDownload > "); err == nil {
				line.AppendHistory(cmd)
				cmdArgs := args.GetArgs(cmd)
				if len(cmdArgs) == 0 {
					continue
				}
				s := []string{os.Args[0]}
				s = append(s, cmdArgs...)
				line.Close()
				c.App.Run(s)
				line = liner.NewLiner()
			} else if err == liner.ErrPromptAborted {
				break 
			}
		}
		return nil 
	}

    app.Run(os.Args)

}